package juc;

import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ArrayBlockingQueueAndLinkedBlockingQueueTest {

	@Test
	public void test() throws InterruptedException {
		final BlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(10000000);
		Thread t1 = new Thread(new Taker(arrayBlockingQueue), "arrayBlockingQueueTaker");
		Thread t2 = new Thread(new Puter(arrayBlockingQueue), "arrayBlockingQueuePuter");
		long start1 = System.currentTimeMillis();
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		System.out.println("arrayBlockingQueue消耗时间：" + (System.currentTimeMillis() - start1));

		final BlockingQueue linkedBlockingQueue = new LinkedBlockingQueue(10000000);
		Thread t3 = new Thread(new Taker(linkedBlockingQueue), "linkedBlockingQueueTaker");
		Thread t4 = new Thread(new Puter(linkedBlockingQueue), "linkedBlockingQueuePuter");
		long start2 = System.currentTimeMillis();
		t3.start();
		t4.start();
		t3.join();
		t4.join();
		System.out.println("linkedBlockingQueue消耗时间：" + (System.currentTimeMillis() - start2));
	}

	class Taker implements Runnable {

		private BlockingQueue blockingQueue;

		Taker(BlockingQueue blockingQueue) {
			this.blockingQueue = blockingQueue;
		}

		@Override
		public void run() {
			for (int i = 0; i < 100000; i++) {
				try {
					blockingQueue.take();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class Puter implements Runnable {

		private BlockingQueue blockingQueue;

		Puter(BlockingQueue blockingQueue) {
			this.blockingQueue = blockingQueue;
		}

		@Override
		public void run() {
			for (int i = 0; i < 10000000; i++) {
				try {
					blockingQueue.put("product");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
